package com.gy.config;

import com.baidu.aip.ocr.AipOcr;
import jakarta.annotation.PostConstruct;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Component
public class BaiduOcrConfig {
    private static final Logger log = LoggerFactory.getLogger(BaiduOcrConfig.class);

    // 百度OCR配置参数（从配置文件读取）
    @Value("${baidu.ocr.api-key}")
    private String apiKey;

    @Value("${baidu.ocr.secret-key}")
    private String secretKey;

    @Value("${baidu.ocr.app-id:}")
    private String appId;

    // 单例OCR客户端
    private AipOcr aipOcrClient;

    /**
     * 初始化OCR客户端（Bean创建时执行）
     */
    @PostConstruct
    public void initAipOcrClient() {
        if (appId == null || appId.isBlank() || apiKey == null || apiKey.isBlank() || secretKey == null || secretKey.isBlank()) {
            log.error("百度OCR初始化失败：配置参数不完整");
            throw new RuntimeException("百度OCR配置错误，请检查appId、apiKey、secretKey");
        }
        aipOcrClient = new AipOcr(appId, apiKey, secretKey);
        aipOcrClient.setConnectionTimeoutInMillis(30000);
        aipOcrClient.setSocketTimeoutInMillis(60000);
        log.info("百度OCR客户端初始化成功（SDK 4.16.10）");
    }

    /**
     * 处理上传的图片并识别文本
     */
    public String imageToText(MultipartFile imageFile) {
        if (imageFile.isEmpty()) {
            throw new IllegalArgumentException("图片文件不能为空");
        }

        String contentType = imageFile.getContentType();
        if (!"image/jpeg".equals(contentType) && !"image/png".equals(contentType) && !"image/jpg".equals(contentType)) {
            throw new IllegalArgumentException("仅支持JPG、PNG格式图片");
        }

        try {
            // 图片流转字节数组（直接适配SDK 4.x的byte[]参数）
            BufferedImage image = ImageIO.read(imageFile.getInputStream());
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            String imageFormat = "png";
            if ("image/jpeg".equals(contentType) || "image/jpg".equals(contentType)) {
                imageFormat = "jpg";
            }
            ImageIO.write(image, imageFormat, bos);
            byte[] imageBytes = bos.toByteArray();
            log.info("图片转换完成，大小：{}KB", imageBytes.length / 1024);

            return recognizeImageBytes(imageBytes);
        } catch (IOException e) {
            log.error("图片处理失败", e);
            throw new RuntimeException("图片读取异常：" + e.getMessage());
        }
    }

    /**
     * 核心方法：用字节数组调用OCR接口（SDK 4.16.10唯一支持的方式）
     */
    public String recognizeImageBytes(byte[] imageBytes) {
        if (imageBytes == null || imageBytes.length == 0) {
            throw new IllegalArgumentException("图片字节流不能为空");
        }
        if (aipOcrClient == null) {
            throw new RuntimeException("OCR客户端未初始化");
        }

        try {
            HashMap<String, String> options = new HashMap<>();
            options.put("language_type", "CHN_ENG");
            options.put("detect_direction", "true");
            options.put("probability", "false");

            JSONObject response = aipOcrClient.basicGeneral(imageBytes, options);

            if (response.has("error_code")) {
                throw new RuntimeException("识别失败：" + response.getString("error_msg"));
            }

            StringBuilder result = new StringBuilder();
            var wordsArray = response.getJSONArray("words_result");
            for (int i = 0; i < wordsArray.length(); i++) {
                result.append(wordsArray.getJSONObject(i).getString("words")).append("\n");
            }
            return result.toString().trim();
        } catch (Exception e) {
            log.error("OCR处理异常", e);
            throw new RuntimeException("识别异常：" + e.getMessage());
        }
    }


}
